<template>
  <div class="boardBox22">
    <div class="flex">
      <div class="flex-1 flex box-row-column ggpadzy20" v-if="isurl">
        <div class="font17">应用凭证</div>
        <el-form ref="queryForm" label-width="100px" class="mt20" :model="queryParams" :rules="rules">
          <el-form-item label="AgentId:" prop="agent_id">
            <el-input v-model="queryParams.agent_id" placeholder="AgentId" clearable type="password" show-password />
          </el-form-item>
          <el-form-item label="AppKey:" prop="app_key">
            <el-input v-model="queryParams.app_key" placeholder="AppKey" clearable type="password" show-password />
          </el-form-item>
          <el-form-item label="AppSecret:" prop="app_secret">
            <el-input v-model="queryParams.app_secret" placeholder="AppSecret" clearable type="password" show-password />
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer mt20" style="text-align: right">
          <el-button type="primary" color="#01509f" @click="submitForm" style="font-size: 13px">绑定</el-button>
        </span>
      </div>

      <div class="flex-1 flex box-row-column ggpadzy20" v-else>
        <div class="flex box-row-column">
          <div class="font17 flex box-align-center">
            <span>事件订阅：</span>
            <el-popover placement="top-start" title="什么是事件订阅?" :width="200" trigger="hover" :content="cont">
              <template #reference>
                <div><img src="@/assets/image/cf/img13.png" alt="" style="width: 20px; height: 20px" /></div>
              </template>
            </el-popover>
          </div>
          <el-form ref="queryFormding" label-width="100px" class="mt20" :model="Paramsding" :rules="rulesding">
            <el-form-item label="Aes_key:" prop="aes_key">
              <el-input v-model="Paramsding.aes_key" placeholder="aes_key" clearable type="password" show-password />
            </el-form-item>
            <el-form-item label="Token:" prop="token">
              <el-input v-model="Paramsding.token" placeholder="token" clearable type="password" show-password />
            </el-form-item>
          </el-form>

          <span slot="footer" class="dialog-footer mt20" style="text-align: right">
            <el-button color="#01509f" @click="submitding">保存并获取链接</el-button>
          </span>
        </div>
        <div class="flex box-row-column">
          <div style="margin-top: 60px">注：aes_key和token请勿随意更改，若发生改变请及时同步，否则系统无法自动更新员工信息</div>
          <div class="font16" style="margin-top: 60px">专属链接：</div>
          <el-input v-model="urlianjie" placeholder="专属链接" class="input-with-select mt10" v-if="urlianjie">
            <template #append>
              <el-button class="urlbutton" @click="copyText()">复制</el-button>
            </template>
          </el-input>
        </div>
      </div>

      <div class="flex-1 flex box-row-column impborderleft ggpadzy20">
        <div class="flex box-align-center">
          <div class="font16 flex-1">同步步骤</div>

          <div class="down_zi flex box-align-center" @click="downmb">
            <div>查看更多帮助</div>

            <div class="bzpng"></div>
          </div>
        </div>

        <div class="importcontent mt20">
          应用应用凭证绑定：
          <br />

          1.使用管理员账号登录钉钉开放平台，选择钉钉应用——>应用开发——>创建应用
          <br />

          2..应用类型选择H5微应用，应用名称和应用描述自己填写（无规范要求），开发方式选择企业自助开发，点击确认创建
          <br />

          3..创建成功之后，点击应用名称进入应用——>点击应用信息——>将应用凭证的三个信息对应填入输入框——>点击绑定——>立即同步
          <br />

          事件订阅：
          <br />

          1.在对应的应用内——>点击事件与回调——>重置加密aes_key和签名token（之前就有aes_key和token的话直接复制就行）——>填入系统对应的输入框——>点击保存并获取链接——>将链接填入钉钉开发平台的请求网址中——>点击保存即可
          <br />

          2.如果事件订阅的aes_key和token发生变化，需将新的aes_key和token重新输入并保存
          <br />
        </div>
      </div>
    </div>
    <div class="flex box-row-column mt20">
      <div class="flex justify-content-center">
        <el-button color="#01509f" type="primary" @click="submittong">同步员工信息</el-button>
      </div>
      <div class="dtpborder_bottom"></div>

      <div class="font16 mt10">同步记录</div>

      <el-form :inline="true" label-width="80px" class="mt20" :model="searchForm">
        <el-form-item label="员工姓名">
          <el-input v-model="searchForm.keywords" placeholder="员工姓名" clearable style="width: 180px" />
        </el-form-item>

        <el-form-item label="日期：">
          <el-date-picker
            v-model="datetime"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 260px"
            @change="dateChange"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" size="mini" color="#01509f" @click="handleQuery">搜索</el-button>
        </el-form-item>
      </el-form>

      <el-table :data="list" border class="mt10" v-loading="loading" element-loading-background="rgba(0, 0, 0, 0.5)" element-loading-text="加载中..." header-row-class-name="table-header">
        <el-table-column label="员工名称" align="center" key="name" prop="name" />
        <el-table-column label="手机号码" align="center" key="mobile" prop="mobile" />
        <el-table-column label="同步内容" align="center" key="remark" prop="remark" />
        <el-table-column label="同步时间" align="center" key="create_time" prop="create_time" />
      </el-table>
      <Pagination :total="total" :current-page="pageInfo.page" :page-size="pageInfo.limit" @pagination-change="handlePaginationChange" />
    </div>

    <el-dialog title="同步员工信息" width="500px" v-model="addvisible" @close="closepross">
      <div class="flex box-row-column ggpadzy20 cc">
        <div class="font16 mb10" v-if="progressStatus === 'success'">同步成功</div>
        <el-progress v-if="showProgress" :percentage="progress" :stroke-width="10" :status="progressStatus" color="#01509f" />
        <div class="font14" v-if="progressStatus === 'success'">同步成功，本次新增{{addperson}}名员工，修改{{updateperson}}名员工，失败{{errorperson}}</div>
      </div>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
  import { ref, reactive, watch, onMounted, nextTick } from "@/TUIKit/adapter-vue";
  import { bind_ding, importEmployees, import_log, company_aes, ding_bind_url, CompanyInfo, template } from "@/api/cf";
  import router from "@/router";
  const props = defineProps({
    visible: {
      type: Boolean,
      default: false,
    },
  });
  const customColor = ref([{ color: "#01509f", percentage: 20 }]);
  import { ElMessageBox, ElLoading, ElMessage, ElProgress } from "element-plus";

  const progress = ref(0); // 进度百分比
  const showProgress = ref(false); // 是否显示进度条
  const progressStatus = ref(""); // 进度条状态（success/error）
  let intervalId: number | null = null; // 定时器 ID
  const jkurl = ref("https://demo-api.niuyuwang.com/");
  const deptoptions = ref([]);
  const job_modeoptions = ref([]);
  const list = ref([]);
  const queryParams = ref({ app_key: "", app_secret: "", agent_id: "" });
  const searchForm = ref({ keywords: "", starttime: "", endtime: "" });
  const emit = defineEmits<{ (event: "update:visible", value: boolean): void; (event: "chananniu", value: ""): void; (event: "success", value: ""): void ; (event: "changeupload", value: ""): void}>();
  const addperson = ref(0);
  const updateperson = ref(0);
  const errorperson = ref(0);
  const pageInfo = ref({ page: 1, limit: 10 });
  const total = ref(0);
  const rules = reactive({
    agent_id: [{ required: true, message: "请填写AgentId", trigger: "blur" }],
    app_key: [{ required: true, message: "请填写AppKey", trigger: "blur" }],
    app_secret: [{ required: true, message: "请填写appsecret", trigger: "blur" }],
  });
  const Paramsding = ref({ aes_key: "", token: "" });
  const rulesding = reactive({
    token: [{ required: true, message: "请填写token", trigger: "blur" }],
    aes_key: [{ required: true, message: "请填写aes_key", trigger: "blur" }],
  });
  // 监听 localValue 的变化，通知父组件更新值
  watch(
    () => props.visible,
    newValue => {
      if (newValue) {
        getDepartmentlist().then(res => {
          deptoptions.value = res.data;
        });
      }
    }
  );
  const cont = ref("当应用凭证绑定之后，使用事件订阅的aes_key和token获取到专属链接，然后在钉钉开发平台绑定链接保存，当员工信息发生更变时，系统将会自动同步员工更新的信息。");
  const addvisible = ref(false);
  const datetime = ref([]);
  const selectedArrRef = ref(null);
  const urlianjie = ref("");
  const isurl = ref(true);
  const handlePaginationChange = ({ page, size }: { page: number; size: number }) => {
    pageInfo.value.page = page;
    pageInfo.value.limit = size;
    list.value = [];
    getimport_log();
  };

  function getimport_log() {
    const data = {
      name: searchForm.value.keywords,

      // starttime: datetime.value.length > 0 ? datetime.value[0] : "",
      // endtime: datetime.value.length > 0 ? datetime.value[1] : "",
      times: datetime.value.length > 0 ? datetime.value : [],
      type: 2,
      page: pageInfo.value.page,
      limit: pageInfo.value.limit,
    };

    import_log(data).then(res => {
      list.value = res.data.list;
      total.value = res.data.total;
    });
  }

  function dateChange(value) {
    if (value === null || value === "") {
      console.log("Date cleared");

      datetime.value = [];
      // 执行你的代码
    }
  }
  function downmb() {
    // template().then(res => {
    //   const url= res.data.$dingTalkDr

    //     router.push({
    //   path: "/pdfdetail",
    //   query: {url}, // 传递查询参数
    // });
    //});

    const url = jkurl.value + "钉钉自动同步设置操作指南.pdf";
    router.push({
      path: "/pdfdetail",
      query: { url },
    });
  }
  function copyText() {
    //获取需要复制的文本内容。
    const text = urlianjie.value;
    // 创建一个临时的 textarea 元素。
    const el = document.createElement("textarea");
    // 将需要复制的文本内容赋值给 textarea 元素。
    el.value = text;
    //将 textarea 元素添加到页面中。
    document.body.appendChild(el);
    //选中 textarea 元素中的文本。
    el.select();
    // 执行复制命令，将选中的文本复制到剪贴板
    document.execCommand("copy");
    //从页面中移除 textarea 元素。
    document.body.removeChild(el);
    //弹出提示框，告知用户文本已复制成功。
    alert("文本已复制");
  }
  function handleQuery() {
    pageInfo.value.page = 1;
    pageInfo.value.limit = 10;
    list.value = [];
    getimport_log();
  }

  function handleChange(value) {
    selectedArrRef.value.togglePopperVisible();
  }
  function cancel() {
    emit("update:visible", false);

    emit("chananniu", "");

  }

  onMounted(() => {
    // 监听窗口大小变化事件以支持响应式
  });
  const queryForm = ref(null);
  const queryFormding = ref(null);

  function submitForm() {
    // isurl.value = false;
    // return false;
    queryForm.value.validate(valid => {
      if (valid) {
        ElMessageBox.confirm("是否要更新并保存AgentId和Appsecret?", "提示", {
          confirmButtonText: "更新并保存",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            bind_ding(queryParams.value).then(res => {
              ElMessage({
                message: res.msg,
                grouping: true,
                type: "success",
              });

              isurl.value = false;
              queryParams.value.app_key = "";
              queryParams.value.app_secret = "";
              queryParams.value.agent_id = "";
            });
          })
          .catch(() => {});
      } else {
        console.log("表单验证失败");
        return false;
      }
    });
  }

  function submitding() {
    queryFormding.value.validate(valid => {
      if (valid) {
        ElMessageBox.confirm("是否要更新并保存Aes_key和Token?", "提示", {
          confirmButtonText: "更新并保存",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            company_aes(Paramsding.value).then(res => {
              ElMessage({
                message: res.msg,
                grouping: true,
                type: "success",
              });
              const data2 = { aes_key: "", token: "" };
              Paramsding.value = data2;
              if (res.code == 1) {
                ding_bind_url().then(res => {
                  urlianjie.value = res.data.url;
                });
              }
            });
          })
          .catch(() => {});
      } else {
        console.log("表单验证失败");
        return false;
      }
    });
  }

  function submittong() {
    ElMessageBox.confirm("是否确定同步员工信息?", "操作提示", {
      distinguishCancelAndClose: true,
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      confirmButtonClass: "ExitConfirmButton",
    }).then((action: Action) => {
      if (action === "confirm") {
        addvisible.value = true;
        // 启动假进度条
        startFakeProgress();
        // const loading = ElLoading.service({
        //   lock: true,
        //   text: "同步中员工信息中……",
        //   background: "rgba(0, 0, 0, 0.3)",
        // });

        importEmployees()
          .then(res => {
            // 接口完成时进度条到 100%
            progress.value = 100;
            progressStatus.value = "success";
             addperson.value = res.data.newCount
             updateperson.value = res.data.updateCount
             errorperson.value = res.data.fail
             
          //  loading.close();
            //handleQuery();
            ElMessage({
              message: "同步成功",
              grouping: true,
              type: "success",
            });
           // emit("success", "");
          })
          .catch(err => {
            // 失败时进度条变红
            progressStatus.value = "error";
           // loading.close();
          })
          .finally(() => {
            // 清理定时器
            if (intervalId) clearInterval(intervalId);
            // 3秒后隐藏进度条
            // setTimeout(() => {
            //   showProgress.value = false;
            // }, 3000);
          });
      }
    });
  }

const closepross = () => {  

  showProgress.value = false;
  progress.value = 0;
  progressStatus.value = "";
  addvisible.value = false
  handleQuery();
   emit("changeupload", "");
  }
  // 启动假进度条
  const startFakeProgress = () => {
    showProgress.value = true;
    progress.value = 0;
    progressStatus.value = "";

    // 定时器模拟进度增长
    intervalId = setInterval(() => {
      if (progress.value < 90) {
        progress.value += Math.floor(Math.random() * 5) + 1;
      }
    }, 200);
  };

  const childMethod = () => {
    const data = { app_key: "", app_secret: "", agent_id: "" };
    const data1 = { keywords: "", starttime: "", endtime: "" };
    const data2 = { aes_key: "", token: "" };
    Paramsding.value = data2;
    queryParams.value = data;
    searchForm.value = data1;
    pageInfo.value.page = 1;
    pageInfo.value.limit = 10;
    list.value = [];
    isurl.value = true;
    urlianjie.value = "";

    nextTick(() => {
      const isaid = localStorage.getItem("agent_id");
      if (isaid == "null") {
        isurl.value = true;
      } else {
        isurl.value = false;
        ding_bind_url().then(res => {
          urlianjie.value = res.data.url;
        });
        const aesinfo = JSON.parse(localStorage.getItem("aesinfo"));

        Paramsding.value.aes_key = aesinfo.aes_key;
        Paramsding.value.token = aesinfo.token;
      }
    });
  };

  defineExpose({
    childMethod,
  });
</script>
 <style>
.cc .el-progress__text {
  min-width: auto;
}

.cc .el-progress__text i {
  color: #01509f;
  /* 将成功图标改为红色 */

  /* 调整图标大小 */
}
</style>
<style lang="scss" scoped>
.boardBox22 {
  display: flex;
  flex-direction: column;

  overflow-y: scroll;
  max-height: calc(100vh - 210px);
  color: #333;

  &::-webkit-scrollbar {
    display: none;
  }

  -ms-overflow-style: none;
  scrollbar-width: none;

  .tishi {
    font-size: 14px;
    color: #999;
    background-color: #f3f8fb;
    padding: 5px 10px;
    border-radius: 6px;
  }

  .font16 {
    font-size: 16px;
  }

  .impborderleft {
    border-left: 1px solid #eaeaea;
  }

  .down_zi {
    font-size: 16px;
    color: #01509f;
    cursor: pointer;
  }

  .uploadk {
    border-radius: 8px;
    border: 1px dashed #f5f5f5;
    padding: 20px 0px;
    font-size: 14px;
    color: #999;
  }

  .avatar-uploader {
    width: 100%;
    text-align: center;
  }

  .impzi1 {
    font-size: 16px;
    color: #666;
  }

  .impzi2 {
    font-size: 14px;
    color: #999;
  }

  .importcontent {
    padding: 20px;
    display: flex;
    flex-wrap: wrap;
    font-size: 15px;
    color: #666;
    background-color: #f3f8fb;
    border-radius: 8px;
    line-height: 25px;
  }

  .dtpborder_bottom {
    border-bottom: 1px solid #eaeaea;
    padding-bottom: 10px;
    padding-top: 10px;
  }

  .urlbutton {
    background-color: #01509f;
    color: #fff;
    border: none;
    border-radius: 0px 5px 5px 0px;
  }

  .bzpng {
    width: 16px;
    height: 16px;
    background: url(@/assets/image/cf/img07.png) no-repeat center center;

    background-size: 15px 15px;
    margin-top: 2px;
  }
}
</style>

<style lang="scss">
.boardBox1 .el-upload {
  width: auto !important;
}

.el-popover__title {
  // 在这里修改
  font-size: 15px;
}
</style>
